//
//  LoginViewController.swift
//  JiaXiaoTong
//
//  Created by 沈增光 on 2018/2/6.
//  Copyright © 2018年 IT. All rights reserved.
//

import UIKit

class LoginViewController: BaseViewController {
    // 用户名
    let frame = CGRect(x: W(x: 65.5), y: H(y: 276.5), width: W(x: 244.5), height: H(y: 33))
   
    let framePassWord = CGRect(x: W(x: 65.5), y: H(y: 319), width: W(x: 244.5), height: H(y: 33))
   
    let frameLogin  = CGRect(x: W(x: 44.5), y: H(y: 377.0), width: W(x: 286), height: H(y: 43))
    let valueFont = CGFloat( Double(getLanguageManageKey(key: "textFont"))!)
    
    
    lazy var accountNum : UITextField  = UITextField(frame:frame  , fontfloat:font(a: valueFont)  , placeholder: getLanguageManageKey(key: "Account"), color: "#33ade6", yesOrNo: false,leftImage:"ico_user" )
 
    ///密码
    lazy var txtPassWord : UITextField  = UITextField(frame: framePassWord , fontfloat: font(a: valueFont), placeholder: getLanguageManageKey(key: "Password"), color: "#33ade6", yesOrNo: true, leftImage: "ico_mima")
    //账户登录按钮
    lazy var accountLoginBtn : UIButton = UIButton(frame: frameLogin , borderWidth: 1, color: UIColor(patternImage: UIImage.init(named: "btn_Code_bg")!), cornerRadiusScale: 0.5, languageKey: "Login")
    // /**老师和家长*/
    lazy var teachers = [String]()
    // /**当前按钮*/
    lazy var btn = UIButton(languagKey: "Language", normalbgImageName: "Teachers", selectbgImageName: "parents_img", enNormalbgImageName: "TeacherPort", enSelectbgImageName: "ParentsPort")
    // /**家长按钮*/
    lazy var phone = UIButton(languagKey: "Language", normalImageName: "phoneAndCode", selectImageName: "userAndpwd", enNormalImageName: "enmessagecode", enSelectImageName: "messagepassword")
    //  /**验证码按钮*/
    lazy var codeBtn = UIButton(bgImageName: "btn_Code_bg", yDistance: self.txtPassWord.y, languageKey: "Get Code", fontValue: 14, cornerRadiusScale: 0.5)
    //
    var verificationCode:String?
    var codeDic = [String : NSObject]()
    // 图像
    lazy var logoImageView =  UIImageView(frame: self.view.bounds, imageName: "login_bg_img")
        
        
    
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
           PAGENUM = 0
        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor(patternImage: UIImage.init(named: "jxloginbg")!)
        NSObject.tp_setInteger(0, forKey: "teacherIndex")
       
      
       self.createLoginView() 
    }
    
    //MARK: - 创建UI
    func createLoginView(){
        NSObject.tp_setInteger(0, forKey: "teacherIndex")
         self.view.backgroundColor = UIColor(patternImage: UIImage.init(named: "btn_Code_bg")!)
        self.view.addSubview(logoImageView)
        self.view.addSubview(accountNum)
        self.accountNum.keyboardType = UIKeyboardType.phonePad
        self.accountNum.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
        
        self.txtPassWord .keyboardType = UIKeyboardType.asciiCapable
        self.txtPassWord.addTarget(self, action:#selector(textFieldPassWordDidChange(_:)) , for: UIControlEvents.editingChanged)
        self.view.addSubview(self.txtPassWord)
        self.codeBtn.width += 10 ;
        self.codeBtn.x = self.accountNum.maxX-self.codeBtn.width
        self.codeBtn.isHidden = true
        self.codeBtn.addTarget(self, action: #selector(codeBntAction(_:)), for:.touchUpInside)
        self.view.addSubview(self.codeBtn)
        self.phone.x = self.accountNum.x + W(x: 20)
        self.phone.y = self.accountNum.y - self.phone.height - 5
        self.phone.isHidden = true
        self.phone.addTarget(self, action: #selector(phoneAndCode(_:)), for: .touchUpInside)
         self.view.addSubview(self.phone)
        self.accountLoginBtn.addTarget(self, action: #selector(loginBtnSendAction(_:)), for: .touchUpInside)
         self.view.addSubview(self.accountLoginBtn)
        
       self.btn.y = 40
       self.btn.x = TPWidth - btn.width - 15
        btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        self.view.addSubview(self.btn)

        self.btnClick(self.btn)
      
        

    }
   
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }
    // 限制用户名 11 位
    @objc  func textFieldDidChange(_ textField:UITextField){
        if (textField.text != nil){
            if ((textField.text! as NSString).length  > 11 ){
               
                MBProgressHUD.showSuccess(getLanguageManageKey(key: "Only 11 mobile phone Numbers can be entered!"))
                textField.text =  (textField.text! as NSString).substring(to: 11)
            
            }
        }
    }
    //限制密码的位数
   @objc  func textFieldPassWordDidChange(_ textField:UITextField)
   {
         var  num : Int?
         num   =  (self.phone.isSelected) ? 6 : 12
         let  showText = self.phone.isSelected ? getLanguageManageKey(key: "The verification code cannot exceed 6 figures") :getLanguageManageKey(key: "The password cannot exceed 12 digits")
        if  (textField.text != nil && num != nil)
        {
        if ((textField.text! as NSString).length > num!){
           self.view.endEditing(true)
           MBProgressHUD.showSuccess(showText)
        textField.text = (textField.text! as NSString).substring(to: num!)
        }
        }
   

    }
    //codebnt
    @objc func codeBntAction(_ bnt : UIButton){
        
    
        
    }
    //手机
    @objc func phoneAndCode(_ button : UIButton){
         button.isSelected = !(button.isSelected)
        self.txtPassWord.text = ""
        self.accountNum.placeholder =  !(button.isSelected) ? getLanguageManageKey(key: "Account") :getLanguageManageKey(key: "Phone number")
        if( button.isSelected){
            self.txtPassWord.width = self.accountNum.width - self.codeBtn.width - 10;
            self.codeBtn.isHidden =  false
           
        } else {
            self.txtPassWord.width = self.accountNum.width
            self.codeBtn.isHidden = true
            
        }
        

        
    }
    //登录
    @objc func loginBtnSendAction(_ button:UIButton){
        
        guard  self.phone.isSelected == false else {
            // 教师端
            self.phoneSelectTheClient(accountKey: "Phone number", txtPassWord: "verification cannot be empty")
            return
        }
        // 家长端
        self.phoneSelectTheClient(accountKey: "Phone number", txtPassWord: "Phone number")
       // 判断手机号的正确性
        var url = ""
        let  params = NSMutableDictionary.init()
        let index = NSObject.tp_integer(forKey: "teacherIndex")//t(forKey: "teacherIndex")
         //家长登录 手机和验证码登录
        if (self.phone.isSelected){
            if (!(self.txtPassWord.text == (self.codeDic[self.accountNum.text!] as! String))){
                MBProgressHUD.showSuccess(getLanguageManageKey(key: "Verification code error"))
                
                return
            }
            let dic  = ["contactPhone":self.accountNum.text]
            params["data"] = dic
            url  = student_jxtStudentLoginByAccount
            NSObject.tp_setInteger(0, forKey: "ClassCourseIndex")
        }else {//老师或者家长登录 手机和密码登录
            NSObject.tp_setInteger(0, forKey: "ClassCourseIndex")
            
            let key = 20171111
            let str  = PassWordManageTool.encrypt(self.txtPassWord.text, withKey: Int32(key))          
            let dic:[String:String?]  = (index == 0) ? (["account":self.accountNum.text!,"pwd":str! ,"identify":identify]) : (["contactPhone":self.accountNum.text!,"studentPwd":str,"identify":identify])
             params["data"] = dic
            url = (index == 0 ) ? teacherUserLogin  : student_jxtStudentLogin

        }
        //let urlString  =  HEADURL +  url
        params["source"]  = "IOS"
        LoginViewMode.shareUserLogin.loginUserInfo(url: url, params: params) {
            for  view in self.view.subviews {
                view.removeFromSuperview()
            }
             self.view.backgroundColor = UIColor.clear
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBSwitchRootViewControllerNotification), object: nil)

        }
//        TPHttpTool.sharedTools.request(method: HMRequestMethod.POST, URLString: urlString, parameters: params) { (progess, responseObj, error) in
//
//            print(responseObj as Any)
//        }


//        [[TPHttpTool manager] requestWithMethod:@"post" url:url params:params inView:self success:^(id responseObj) {
//        //         NSLog(@"========%@",responseObj);
//        if ([responseObj[@"msg"] isEqualToString:@"OK"]) {
//        NSDictionary *result = responseObj[@"result"];
//        //            储存用户信息
//        if (index==0) {//老师登录
//        UserInfoModel *userinfo = [UserInfoModel mj_objectWithKeyValues:result];
//        userinfo.userId = result[@"id"];
//        [UserTool saveUserInfo:userinfo];
//        //  NSLog(@"老师登录%@",result);
//        }else{//家长登录
//        Parents *parent = [Parents mj_objectWithKeyValues:result];
//        [UserTool saveParents:parent];
//        }
//        [UserTool notiWithState:@"login"];
//        for (UIView *view in self.view.subviews) {
//        [view removeFromSuperview];
//        }
//        self.view.backgroundColor = [UIColor clearColor];
//
//        [UIApplication sharedApplication].keyWindow.rootViewController = [[BaseTabBarController alloc]init];
//        [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
//
//        }else{
//
//        NSString *str = @"";
//        if (NULLString(responseObj[@"msg"])) {
//        str = getLanguageManageKey(@"Invalid account, please confirm and lose again");
//        }else{
//        str = [NSString stringWithFormat:@"%@",responseObj[@"msg"]];
//        }
//        [MBProgressHUD showSuccess:str];
//        }
//
//
//        } failure:^(NSError *error) {
//        NSLog(@"%@",error);
//        }];
//
        
    }
    //
    @objc func btnClick(_ button: UIButton){
        self.view.endEditing(true)
        button.isSelected = !(button.isSelected)
        let imgName = button.isSelected ? "login_Other_bg_img" : "login_bg_img"
        self.accountNum.keyboardType = button.isSelected ? UIKeyboardType.phonePad : UIKeyboardType.asciiCapable
        self.logoImageView.image = UIImage.init(named: imgName)
        self.txtPassWord.text = ""
        self.codeBtn.isHidden = true
        self.txtPassWord.width = self.accountNum.width 
        self.accountNum.placeholder = getLanguageManageKey(key: "Account")
        self.txtPassWord.placeholder = getLanguageManageKey(key: "Password")
        self.phone.isHidden = !(button.isSelected)
        self.phone.isSelected = false
   
            let saveSelect = (button.isSelected) ? (1) : (0)
        NSObject.tp_setInteger(saveSelect, forKey: "teacherIndex")


        
    }
}
extension LoginViewController {
    
    override var shouldAutorotate: Bool{
        
        return false
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
    return UIInterfaceOrientationMask.portrait
    }
    func phoneSelectTheClient(accountKey:String,txtPassWord:String){
        
        if ((self.accountNum.text! as NSString).length < 1 ){
            
            MBProgressHUD.showSuccess(getLanguageManageKey(key: accountKey))
            return
        }else if ((self.txtPassWord.text! as NSString).length < 1){
            
            MBProgressHUD.showSuccess(getLanguageManageKey(key: txtPassWord))
        }
        
    }


    
    
}
